package com.edu.service.impl;

import com.edu.dao.CommentDao;
import com.edu.dao.UserDao;
import com.edu.dao.impl.CommentDaoImpl;
import com.edu.dao.impl.UserDaoImpl;
import com.edu.entity.CommentEntity;
import com.edu.service.CommentService;
import com.edu.utils.JwtUtils;

import java.util.LinkedList;
import java.util.Map;

/**
 * com.edu.service.impl
 * 2024/7/14 14:53
 *
 * @author Fancy
 * @version 1.0
 */
public class CommentServiceImpl implements CommentService {
    CommentDao commentDao = new CommentDaoImpl();
    UserDao userDao = new UserDaoImpl();
    @Override
    public int addComment(CommentEntity comment) {
        return commentDao.addComment(comment);
    }

    @Override
    public int deleteReview(int reviewId, String token) {
        Map<String, Object> user = JwtUtils.validateToken(token);
        try {
            if (user.get("role").equals("admin")){
                //管理员有权删除所有评论
                return commentDao.deleteReview(reviewId);
            } else {
                //判断删除评论的人和发表评论的人是否是同一个
                if(userDao.getUserByEmail((String) user.get("email")).getUserId() == commentDao.getCommentById(reviewId).getUserId()){
                    return commentDao.deleteReview(reviewId);
                } else {
                    return 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public LinkedList<CommentEntity> getReviewsByBookId(int bookId) {
        return commentDao.getBookReviewsByBookId(bookId);
    }
}
